<?php

class base_setup_lock {

    private $lockcode_prefix = "If you want to reinstall system, delete this file! <?php exit();?> \ncode: ";

    private $codecookie_name = '_ecos_setup_lockcode';

    private function lockfile() {
        if (ECAE_MODE) {
            return 'ecos.install.lock';
        } else {
            return ROOT_DIR . '/config/install.lock.php';
        }
    }
 // End Function
    private function put_lockfile($content) {
        if (ECAE_MODE) {
            return app::get('base')->setConf($this->lockfile(), $content);
        } else {
            return file_put_contents($this->lockfile(), $content);
        }
    }
 // End Function
    private function get_lockfile() {
        if (ECAE_MODE) {
            return app::get('base')->getConf($this->lockfile());
        } else {
            return file_get_contents($this->lockfile());
        }
    }
 // End Function
    public function lockfile_exists() {
        if (ECAE_MODE) {
            return (app::get('base')->getConf($this->lockfile())) ? true : false;
        } else {
            return file_exists($this->lockfile());
        }
    }
 // End Function
    public function write_lock_file($cookie = true) {
        $lock_code = md5(microtime()) . md5(print_r($_SERVER, 1));
        if ($this->put_lockfile($this->lockcode_prefix . $lock_code)) {
            $path = kernel::base_url();
            $path = $path ? $path : '/';
            if ($cookie)
                setcookie($this->codecookie_name, $lock_code, 0, $path);
            return true;
        } else {
            return false;
        }
    }

    public function get_lock_code() {
        $content = $this->get_lockfile($this->lockfile());
        $ncode = substr($content, strlen($this->lockcode_prefix));
        return $ncode;
    }
 // End Function
    public function check_lock_code() {
        if (isset($_COOKIE[$this->codecookie_name])) {
            $code = $this->get_lock_code();
            if ($code && $this->get_lock_code() === $_COOKIE[$this->codecookie_name]) {
                return true;
            }
        }
        return false;
    } // End Function
}//End Class